/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.anniversary.domain.Association;
import me.zhengjie.modules.anniversary.repository.AssociationRepository;
import me.zhengjie.modules.anniversary.service.AssociationService;
import me.zhengjie.modules.anniversary.service.dto.AssociationDto;
import me.zhengjie.modules.anniversary.service.dto.AssociationQueryCriteria;
import me.zhengjie.modules.anniversary.service.mapstruct.AssociationMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Jiayin Wei
* @date 2020-07-28
**/
@Service
@RequiredArgsConstructor
public class AssociationServiceImpl implements AssociationService {

    private final AssociationRepository associationRepository;
    private final AssociationMapper associationMapper;

    @Override
    public Map<String,Object> queryAll(AssociationQueryCriteria criteria, Pageable pageable){
        Page<Association> page = associationRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(associationMapper::toDto));
    }

    @Override
    public List<AssociationDto> queryAll(AssociationQueryCriteria criteria){
        return associationMapper.toDto(associationRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AssociationDto findById(Long id) {
        Association association = associationRepository.findById(id).orElseGet(Association::new);
        ValidationUtil.isNull(association.getId(),"Association","id",id);
        return associationMapper.toDto(association);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AssociationDto create(Association resources) {
        return associationMapper.toDto(associationRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Association resources) {
        Association association = associationRepository.findById(resources.getId()).orElseGet(Association::new);
        ValidationUtil.isNull( association.getId(),"Association","id",resources.getId());
        Long oldReviewerId = association.getReviewerId();
        association.copy(resources);
        if (!oldReviewerId.equals(association.getReviewerId()))
        {
            association.setReviewTime(new Timestamp(System.currentTimeMillis()));
        }
        associationRepository.save(association);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            associationRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AssociationDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AssociationDto association : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", association.getName());
            map.put("创建者", association.getCreater().getUsername());
            map.put("类型（0：行业，1：地域，2：院系）", association.getType());
            map.put("简介", association.getBrief());
            map.put("审核状态", association.getVerifyStatus());
            map.put("审核者", association.getReviewer().getUsername());
            map.put("审核时间", association.getReviewTime());
            map.put("创建者名称", association.getCreateBy());
            map.put("创建时间", association.getCreateTime());
            map.put("修改者名称", association.getUpdatedBy());
            map.put("修改时间", association.getUpdateTime());
            map.put("排序", association.getSort());
            map.put("备注", association.getRemark());
            map.put("状态", association.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}